package com.example.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result;
import com.example.dto.FileVO;
import com.example.entity.Ordersetting;
import com.example.service.OrdersettingService;
import com.example.utils.POIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @date 2021/3/17 10:16
 * @description 文件上传
 */
@RestController
@RequestMapping("/files")
public class FileController {
    @Autowired
    private OrdersettingService ordersettingService;
    /**
     * 单文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
        System.out.println("filePath = " + filePath);
        String flag = System.currentTimeMillis() + "";
        String fileName = file.getOriginalFilename();
        String[] split = fileName.split("\\.");
        String houzhuiming = split[split.length-1];
        String newJpgName = flag + UUID.randomUUID()+"."+houzhuiming;
        try {
            FileUtil.writeBytes(file.getBytes(), filePath + newJpgName);
            System.out.println(fileName + "--上传成功");
            Thread.sleep(1L);
        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
        }
        return Result.success(newJpgName);
    }

    /**
     * 多文件上传
     * @param request
     * @return
     */
//    @PostMapping("/upload/multiple")
//    public Result<List<FileVO>> multipleUpload(HttpServletRequest request) {
//        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
//        String filePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
//        List<FileVO> fileVOS = Lists.newArrayList();
//        for (MultipartFile file : files) {
//            if (file.isEmpty()) {
//                continue;
//            }
//            String flag = System.currentTimeMillis() + "";
//            String fileName = file.getOriginalFilename();
//            FileVO fileVO = new FileVO();
//            fileVO.setFlag(flag);
//            fileVO.setFileName(file.getOriginalFilename());
//            fileVOS.add(fileVO);
//            try {
//                FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
//                System.out.println(fileName + "--上传成功");
//                Thread.sleep(1L);
//            } catch (Exception e) {
//                System.err.println(fileName + "--文件上传失败");
//            }
//
//        }
//        return Result.success(fileVOS);
//    }

    /**
     * 获取文件
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;
        String basePath = System.getProperty("user.dir") + "/src/main/resources/static/file/";
        List<String> fileNames = FileUtil.listFileNames(basePath);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    // excel的上传
     // /files/ordersetting
    @RequestMapping(value = "/ordersetting",method = {RequestMethod.POST})
    public Result ordersettion(@RequestParam("excelFile") MultipartFile excelFile) throws IOException, ParseException {
        System.out.println("excelFile = " + excelFile);
        List<String[]> rows = POIUtils.readExcel(excelFile);
        System.out.println("rows = " + rows);
        List<Ordersetting> ordersettingList = new ArrayList<>();
//        for (String[] row : rows) {
//            System.out.println("row = " + row);
//            for (String cell : row) {
//                System.out.println("cell = " + cell);
//            }
//        }
        for (int i = 0; i < rows.size(); i++) {
            Ordersetting ordersetting = new Ordersetting();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String dateStr = rows.get(i)[0];
            String number = rows.get(i)[1];
            Date parse = sdf.parse(dateStr);
            ordersetting.setOrderDate(parse);
            ordersetting.setNumber(Integer.parseInt(number));
            ordersettingList.add(ordersetting);
        }
        ordersettingService.add(ordersettingList);
        return Result.success();
    }

}
